package com.geeklan.smart.wifi;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

public class WiFiHelper {

    private WifiManager wifiManager;

    public WiFiHelper(Context context) {
        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    }

    // 连接到指定AP
    public boolean connectToWifi(String ssid, String password) {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();
        wifiConfiguration.SSID = "\"" + ssid + "\"";  // SSID必须是带引号的
        wifiConfiguration.preSharedKey = "\"" + password + "\"";  // WPA2密码

        int networkId = wifiManager.addNetwork(wifiConfiguration);
        if (networkId == -1) {
            return false;  // 添加网络失败
        }

        return wifiManager.enableNetwork(networkId, true);  // 启用网络连接
    }

    // 获取当前连接的Wi-Fi信息
    public String getCurrentConnectedSSID() {
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        return wifiInfo.getSSID();
    }

    // 断开当前连接的Wi-Fi
    public boolean disconnectCurrentNetwork() {
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int networkId = wifiInfo.getNetworkId();
        return wifiManager.disableNetwork(networkId);
    }
}

